package com.woniuxy.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.dto.ContactVO;
import com.woniuxy.merchant.entity.ChatMessage;
import com.woniuxy.merchant.mapper.ChatMessageMapper;
import com.woniuxy.merchant.service.IChatMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-13
 */
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements IChatMessageService {
    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Override
    public List<ChatMessage> getChatHistory(Integer userId) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("sender_id", userId)
                .or()
                .eq("receiver_id", userId)
                .orderByAsc("timestamp");

        return this.list(queryWrapper);
    }

    @Override
    public List<ContactVO> queryToInfo(Integer userId) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ChatMessage::getSenderId, userId)
                .or()
                .eq(ChatMessage::getReceiverId, userId);

        List<ChatMessage> messages = chatMessageMapper.selectList(queryWrapper);

        Map<Integer, ContactVO> contactMap = new HashMap<>();

        for (ChatMessage msg : messages) {
            // 如果当前用户是发送者，联系人是接收者
            if (msg.getSenderId().equals(Integer.valueOf(userId))) {
                Integer contactId = msg.getReceiverId();
                if (!contactMap.containsKey(contactId)) {
                    contactMap.put(contactId, new ContactVO(
                            contactId,
                            msg.getReceiverName(),
                            msg.getReceiverAvatar()
                    ));
                }
            } else {
                // 当前用户是接收者，联系人是发送者
                Integer contactId = msg.getSenderId();
                if (!contactMap.containsKey(contactId)) {
                    contactMap.put(contactId, new ContactVO(
                            contactId,
                            msg.getSenderName(),
                            msg.getSenderAvatar()
                    ));
                }
            }
        }

        return new ArrayList<>(contactMap.values());
    }
}
